<template>
  <div class="biz-container">
    <table-layout :haveSider="false">
      <template #searchBox>
        <search-layout
          v-if="isExit"
          :formInfos="q_formInfos"
          :formDatas="q_formDatas"
          message=""
          @onFind="onFind"
          @onChangeType="onChangeType"
        ></search-layout>
      </template>
      <template #batchOperat>
        <batch-operat-btn 
          :optData="optText" @onOptData="onBatchAudit"
        >
          <template #cusBtn>
            <a-button type="primary" v-if="side=='settlementOrder'" icon="plus-circle"  @click="onAddData" > 新增 </a-button>
            <a-button type="primary" v-if="side=='settlementOrder'" icon="close-circle"  @click="onDelectData" style="marginLeft:20px" > 删除 </a-button>
            <a-button type="primary" v-if="side=='settlementOrder_s'||side=='settlementByDelivery'" icon="reconciliation" @click="onBatchInvoice"> 开票 </a-button>
            
          </template>
        </batch-operat-btn>
      </template>
      <template #tableList="slotData">
        <a-list-table
          :columns="columns"
          :tableData="listdata"
          :pagination="pagination"
          :isSelecttion="true"
          :loading="loading"
          :scroll="{y:slotData.tableHeight}"
          @onTableChange="handleTableChange"
          @onselectChange="onselectChange"
          @onAction="onAction"
          :links="links"
          @onTouchlinkCell="onTouchlinkCell"
        >
        </a-list-table>
        <!-- <drag-box></drag-box> -->
      </template>
    </table-layout>
     <auditModal ref="auditModal" @ok="handleModalSaveOk" @close="handleModalCancel" />
     <viewModal ref="viewModal" @ok="handleModalSaveOk" @close="handleModalCancel" />
     <addModal ref="addModal" @ok="handleModalSaveOk" @close="handleModalCancel" />
     <invoiceModal ref="invoiceModal" @ok="handleModalSaveOk" @close="handleModalCancel" />
     
  </div>
</template>

<script>
import searchLayout from '@/views/app/biz/common/searchLayout'
import dragBox from '@/views/app/biz/common/dragBox'
import batchOperatBtn from '@/views/app/biz/common/batchOperatBtn'
import tableLayout from '@/views/app/biz/common/index'
import aListInfo from '@/views/app/biz/common/aListInfo'
import aListTable from '@/views/app/biz/common/aListTable'
import viewModal from './viewModal'
import invoiceModal from './invoiceModal.vue'
import auditModal from './auditModal'
import addModal from './addModal.vue'
import {
  getByConditions,
  getByConditionsCount,
  deleteInfo
} from './settlement'
import {
  columns1,columns2,columns3,q_formDatas,q_formInfos1,q_formInfos2
} from './dataConfig'

// 字段列表

let links=['settlementNo']

export default {
  components: {
    searchLayout,
    batchOperatBtn,
    tableLayout,
    aListInfo,
    aListTable,
    viewModal,
    auditModal,
    addModal,
    invoiceModal,
    dragBox
  },
  data() {
    return {
      columns: columns1,
      listdata: [],
      links:links,
      loading: false,
      pagination: {
        //分页配置
        current: 1, //当前页码 current
        pageSize: 10, //每页显示条数 pageSize
        total: 1,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ['2', '10', '50', '100'],
      },
      // 查询表单
      q_formInfos: q_formInfos1,
      // 查询表单绑定数据
      q_formDatas:q_formDatas ,
      pData: {}, // 条件查询参数
      isJump:false,
      optText: '',
      selectedRowKeys: [],
      selectedRows: [],
      notAudit: false,
      side:null,
      isExit:true
    }
  },
  computed: {},
  watch: {
    $route: {
        handler: function (val, oldVal) {
          console.log(this.$route.name); 
          console.log(this.$route.meta);  
          //判断是进入该页面还是离开
          if (this.$route.name=='settlementOrder_s' 
            || this.$route.name=='settlementOrder' 
            || this.$route.name=='settlementByDelivery' ) {
            this.side=this.$route.name
            this.judgeSide()
            console.log( this.side);
            //读取该页面是否缓存，未缓存时：
            if (!this.$route.meta.keepAlive) {
              this.isExit=false
              this.$nextTick(()=>{
                this.isExit=true
              })
              //读取页面跳转传参
              if(this.$route.params.keHuPid){
                this.q_formDatas.keHuPid=this.$route.params.keHuPid
              }
              this.q_formDatas.settlementType=this.$route.meta.settlementType
              this.getTotal()
              this.getList(this.q_formDatas)
            }else{
              console.log(this.$route.params.isBack);
              //已缓存时判断是否是返回
              if (!this.$route.params.isBack) {
                this.getTotal()
                this.getList(this.q_formDatas)
              }
              this.isJump=false
            }
          }
        },
        deep: true,
        immediate:true
    }
  },
  beforeRouteEnter(to,from,next){
    console.log('beforeRouteEnter',to,from);
    next(vm=>{
      console.log(vm.isJump);
    });
  },
  beforeRouteLeave(to,from,next){
    if (this.isJump) {
      from.meta.keepAlive=true
    }else{
      from.meta.keepAlive=false
    }
    next();
  },
  mounted(){
    console.log('mounted');
    // this.getTotal()
    // this.getList(this.q_formDatas)
    
  },
  methods: {
    judgeSide(){
      if(this.side=='settlementOrder'){
        this.columns=columns1
        this.q_formInfos= q_formInfos1
      }else if (this.side=='settlementOrder_s') {
        this.columns=columns3
        this.q_formInfos= q_formInfos2
      }else{
        this.columns=columns2
        this.q_formInfos= q_formInfos2
      }
    },
    // 初始化页面时得到总数
    async getTotal() {
      let pages = ''
      pages = await getByConditionsCount(this.q_formDatas)
      console.log(pages)
      if (pages && pages.code && pages.code === 'C1') {
        const pagination = { ...this.pagination }
        pagination.total = pages.data
        this.pagination = pagination
        this.pagination.showTotal =  (showTotal) => {return `共 ${showTotal} 条`}
      }
    },
    // 初始化查询时的数据列表
    async getList(params) {
      console.log('请求列表时传入的数据', params)
      let actionBtn=[]
      this.loading = true
      let listdata = []
      let res = ''
      res = await getByConditions(params, this.pagination)
      this.loading = false
      console.log(res)
      if (res && res.code && res.code === 'C1' && res.data) {
        const resdata = res.data
         for (let item of resdata) {
            // switch (item.invoiceState) {
            //   case '待审核':
            //     actionBtn = ['修改','发票']
            //     break
            //   default:
            //     actionBtn = ['修改','发票']
            // }
            if (this.side=='settlementOrder_s'||this.side=='settlementByDelivery') {
               actionBtn = ['查看']
            }
            if (this.side=='settlementOrder') {
               actionBtn = ['修改','查看']
            }
            listdata.push({
               key: item.pid,
               action:actionBtn ,
               ...item
               }
            )
         }
         this.listdata =listdata
      } else {
        this.listdata = []
      }
      console.log(this.listdata)
    },
    // 新增按钮 点击了新增
    onAddData() {
      // this.$refs.addModal.addModal()
      this.$router.push({
        name: 'addSettlement',
        params: {
          isJump:false,
          pathName:this.$route.name,
          pid:null,
          type:'add'
        } 
      })
    },
    // 关闭模态详细框
    handleModalCancel() {
    },
    // 模态详细框提交按钮
    handleModalSaveOk() {
      this.getList(this.q_formDatas)
    },
    // 操作按钮
    onAction(text, record, index) {
      if (text == '修改') {
        //修改
        // this.$refs.addModal.editModal(record.pid) 
        this.$router.push({
          name: 'addSettlement',
          params: {
            isJump:false,
            pathName:this.$route.name,
            pid:record.pid,
            type:'edit'
          } 
        })
        // this.showConfirm(record)
      }else if (text == '查看'){ 
        this.$refs.viewModal.showModal(record.pid)
      }else if (text == '发票'){ 
        // this.$refs.invoiceModal.showModal(record.pid,record)
        this.isJump=true
        this.$router.push({
          name: 'invoice',
          params: {
            isJump:this.isJump,
            pathName:this.$route.name,
            pid:record.pid
          } 
        })
      }
    },

    // 触发改变页码,筛选,排序时的回调
    handleTableChange(pagination, filters, sorter) {
      this.pagination.current = pagination.current
      this.pagination.pageSize = pagination.pageSize
      this.getList(this.q_formDatas)
    },
    // 搜索栏选择下拉select触发搜索val[0]表示选中的record中的pid,val[1]表示选中的record全部信息
    onChangeType(name, val) {
      console.log('formName',name)
      console.log('val',val)
      switch (name) {
        case 'pid': 
          if (!val[0]) {
            this.q_formDatas.pid=null
          }
          this.onFind ()
          break 
        case 'supplierOrgPid':
          if (!val) {
            this.q_formDatas.supplierOrgPid=null
          }
          this.onFind ()
          break
        case 'customerPid':
          if (!val) {
            this.q_formDatas.customerPid=null
          }
          this.onFind ()
          break
        case 'invoiceType':
          if (!val) {
            this.q_formDatas.invoiceType=null
          }
          this.onFind ()
          break
      }
    },
    // 查询按钮
    onFind (){
      this.pagination.current = 1
      this.getTotal()
      this.getList(this.q_formDatas)
    },

    onTouchlinkCell( text, record, index,link){
      console.log(record);
      if(link=='settlementNo'){
        this.$refs.viewModal.showModal(record.pid)
      }
    },
    // 多选批量操作
    onselectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      for (const item of this.selectedRows) {
        if (item.zhuangTai != '待审核') {
          this.notAudit = true
          return
        } else {
          this.notAudit = false
        }
      }
    },
    onDelectData(){
      if(this.selectedRows.length){
        this.showDelConfirm(this.selectedRows)
      }else{
        this.$message.warning({ content:'未选择要删除的记录', duration: 3 })
      }
    },
    showDelConfirm(val,type) {
      let datas=[]
      if(type=='1'){
        datas[0]=val
      }else{
        datas=val
      }
      const that = this;
      this.$confirm({
        title: '是否确认删除？',
        content: '删除后不可恢复！',
        onOk() {
          let reqArr=[]
          let key='self'
          for (const item of datas) {
            reqArr.push(that.delOrder(item))
          }
          return Promise.all(reqArr).then(res => {
            console.log(res);
            for (const item of res) {
              console.log(item);
              if (item && item.code && item.code === 'C1' && item.data) {
                that.$message.success({ content:'记录删除成功', duration: 3 })
              } else {
                that.$message.error({ content:'记录删除失败，原因：'+item.message, duration: 3 })
              }
            }
            that.handleModalSaveOk()
          }).catch(err => {
            that.$message.error({ content:'操作出错:'+err, duration: 3 })
          })
        },
        onCancel() {},
      });
    },
    async delOrder(val){
      let res = await deleteInfo(val)
      return res
    },
    onBatchAudit() {
      if (this.selectedRows.length) {
        if (this.notAudit) {
          this.$message.warning({ content: '已选项中含有已审核的记录，请选择待审核的记录', duration: 3 })
        } else {
          this.$refs.auditModal.batchModal(this.selectedRows)
        }
      } else {
        this.$message.warning({ content: '未选择要审核的记录', duration: 3 })
      }
    },
    onBatchInvoice() {
      console.log('开票');
      if (this.selectedRows.length) {
        this.$router.push({
          name: 'toInvoicing',
          params: {
            isJump:false,
            pathName:this.$route.name,
            pid:null,
            orderType:'settlement',
            order:this.selectedRows,
            type:'add',
          } ,
        })
      } else {
        this.$message.warning({ content: '未选择要开票的记录', duration: 3 })
      }
    },
  },
}
</script>

<style>
</style>